import axios from "axios";
import React, { Component } from "react";
import PubSub from "pubsub-js";

export default class Search extends Component {
    search = async () => {
        // 获取用户输入(连续解构赋值+重命名)
        const {
            keyWordElement: { value: keyword },
        } = this;
        // 发送请求前通知 List 更新状态
        PubSub.publish("atguigu", {
            isFirst: false,
            isLoading: true,
        });
        // 发送网络请求--使用 fetch 发送
        // fetch(`/api1/search/users2?q=${keyword}`)
        //     .then(
        //         (response) => {
        //             console.log("联系服务器成功了");
        //             return response.json();
        //         },
        //         (err) => {
        //             console.log("联系服务器失败了", err);
        //             return new Promise();
        //         }
        //     )
        //     .then(
        //         (response) => {
        //             console.log("获取数据成功了", response);
        //         },
        //         (error) => {
        //             console.log("获取数据失败了", error);
        //         }
        //     );
        try {
            const response = await fetch(`/api1/search/users2?q=${keyword}`);
            const data = await response.json();
            PubSub.publish("atguigu", { isLoading: false, users: data.items });
        } catch (error) {
            console.log("请求出错了");
            PubSub("atguigu", { isLoading: false, err: error.message });
        }
    };

    render() {
        return (
            <section className="jumbotron">
                <h3 className="jumbotron-heading">Search Github Users</h3>
                <div>
                    <input
                        ref={(c) => (this.keyWordElement = c)}
                        type="text"
                        placeholder="enter the name you search"
                    />
                    <button onClick={this.search}>Search</button>
                </div>
            </section>
        );
    }
}
